|
|
|
In some languages,
variables are initialized to 0 - that is, a variable's initial value will be
0. This is not true of C++! Sometimes your variables will be initialized to
0, but sometimes they will be initialized with garbage. As you might
anticipate, this can cause some nasty bugs. Let's take a look at another
sample program.
|
|
#include
<iostream.h> int main() { int myAge; cout << "My age is
" << myAge << endl; return 0; } You might expect the program to output "My age is 0". In
fact, the output of this program is unreliable. On one system you may get
output of "My age is 11"; another system may output "My age is
0"; yet another system may output "My age is 3145". That's
what it means to have a variable initialized with garbage.
|
|
It is always a good idea to
initialize your variables with some value. If you don't know what a
variable's initial value should be, initialize it to 0. Initializing a
variable is easy. Let's fix the above program so that it always outputs
"My age is 22". The first line of the main function
initializes myAge by assigning it a value immediately.
|
|
#include
<iostream.h> int main() { int myAge = 22; cout << "My age is
" << myAge << endl; return 0; }
|